<template>
    <el-container class="applet">
        <el-main class="wrapper">
            <section class="panel cms-content">
                <div class="panel-body">
                    <el-form :model="formData" label-position="top" ref="formData" label-width="100px"
                             class="demo-ruleForm">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item prop="music_name" :rules="[{ required: true, message: '请填写音乐名称', trigger: 'blur'}]">
                                    <el-input v-model="formData.music_name" placeholder="请填写音乐名称"></el-input>
                                </el-form-item>
                                <el-form-item prop="music" :rules="[{ required: true, message: '请填写音乐编号', trigger: 'blur'}]">
                                    <el-input v-model="formData.music" placeholder="请填写音乐编号"></el-input>
                                </el-form-item>
                                <el-form-item :rules="[{ required: true, message: '请选择背景图', trigger: 'change'}]" class="background" prop="backimg">
                                    <el-popover
                                            placement="right"
                                            width="1000" v-model="backimgsShow"
                                            trigger="click">
                                        <el-row :gutter="20" class="backimgs">
                                            <el-col v-for="item in backimgs" :key="item.id" :span="6"
                                                    style="margin-bottom: 10px">
                                                <el-card :body-style="{ padding: '0px' }">
                                                    <img :src="item.img" style="width:100%;height:85px" alt="">
                                                    <div style="padding: 14px;">
                                                        <span>{{item.title}}</span>
                                                        <el-button @click="select(item)"
                                                                   style="float: right; padding: 3px 0" type="text"
                                                                   class="button">选 择
                                                        </el-button>
                                                    </div>
                                                </el-card>
                                            </el-col>
                                        </el-row>
                                        <el-button type="primary" slot="reference">选择背景图</el-button>
                                    </el-popover>
                                    <el-button class="button" style="margin-left: 20px;">{{backimgsTile}}</el-button>
                                </el-form-item>
                                <el-form-item prop="hot" v-if="userInfo.id==1">
                                    <el-radio-group v-model="formData.hot">
                                        <el-radio border :label="1">正常</el-radio>
                                        <el-radio border :label="2">热门</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item prop="lock">
                                    <el-radio-group v-model="formData.lock">
                                        <el-radio border :label="1">正常</el-radio>
                                        <el-radio border :label="2">锁定</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item prop="status">
                                    <el-radio-group v-model="formData.status">
                                        <el-radio border :label="1">上架</el-radio>
                                        <el-radio border :label="2">下架</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item :rules="[{ required: true, message: '请上传封面图', trigger: 'change'}]" prop="thumb">
                                    <el-upload
                                            class="index-avatar-uploader"
                                            :action="upload"
                                            :headers="myHeaders"
                                            :show-file-list="false"
                                            name="image"
                                            :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                        <img v-if="formData.thumb" :src="formData.thumb"
                                             class="index-avatar">
                                        <i v-else class="el-icon-plus index-avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                                <el-col :span="24" style="color: red;line-height:30px;">
                                    <span>上传封面图片格式只能是 JPG | PNG | GIF</span><br>
                                    <span>上传封面图片大小不能超过 100KB!</span><br>
                                    <span>上传的封面图宽高必须是 360*288 px !</span><br>
                                </el-col>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item :rules="[{ required: true, message: '请填写标题', trigger: 'blur'}]" prop="title">
                                    <el-input style="width: 60%;top:-15px" v-bind:content="formData.title"
                                              v-model="formData.title" placeholder="请填写标题"></el-input>
                                    <el-color-picker
                                            v-model="formData.title_color"
                                            :predefine="predefineColors">
                                    </el-color-picker>
                                </el-form-item>
                                <el-form-item :rules="[{ required: true, message: '请填写内容', trigger: 'blur'}]" prop="content">
                                    <vue-neditor-wrap ref="mobile" v-model="formData.content" @ready="ready"
                                                      :config="myConfig"
                                                      :destroy="false"></vue-neditor-wrap>
                                </el-form-item>
                                <div>
                                    <el-button style="float: right" type="primary" @click="update('formData')">保存发布
                                    </el-button>
                                    <el-button type="primary" @click="goback()">返回列表</el-button>
                                </div>
                            </el-col>
                            <el-col :span="7">
                                <div class="preview-art">
                                    <div class="phone-content"
                                         :style="{'background':formData.backimg ? 'url('+ formData.backimg +')' : '#fff'}">
                                        <div class="phone-content-title"></div>
                                        <div ref="mobile" style="height: 550px;overflow: hidden;overflow-y:scroll;"
                                             v-html="formData.content"></div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </section>
        </el-main>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import {
        BackAll,
        ArticleInfo,
        ArticleUpdate,
        BackUpdate,
        BackDestroy
    } from '@/utils/request';
    import VueNeditorWrap from 'vue-neditor-wrap';
    export default {
        components: {VueNeditorWrap},
        data() {
            return {
                isModify:false,//是否为修改（编辑）文章
                userInfo: this.$storage.get('userinfo'),
                showMsg: 0,//展示显示的文章发布信息
                item: "0",//选择上传或修改文章的名字
                predefineColors: [
                    '#000000',
                    '#FF0000',
                    '#FFFFFF',
                    '#FFFF00',
                    '#00FF00',
                    '#0000FF',
                    '#9F00FF',
                ],
                myConfig: {
                    // 如果需要上传功能,找后端小伙伴要服务器接口地址
                    preserveHeaders:{
                        'Authorization': 'Bearer ' + this.$storage.get('token'),
                        'Accept': 'application/json'
                    },
                    serverUrl: '/manage/upload',
                    // 你的UEditor资源存放的路径,相对于打包后的index.html
                    UEDITOR_HOME_URL: '/NEditor/',
                    // 编辑器不自动被内容撑高
                    autoHeightEnabled: false,
                    // 初始容器高度
                    initialFrameHeight: 540,
                    // 初始容器宽度
                    initialFrameWidth: '100%',
                    // 关闭自动保存
                    enableAutoSave: false,
                    //关闭远程图片是否抓取到本地保存
                    catchRemoteImageEnable: false,
                    //是否启用元素路径，默认是显示
                    elementPathEnabled: false,
                    ////是否开启字数统计
                    wordCount: false,
                    //是否保持toolbar的位置不动,默认true
                    autoFloatEnabled: false
                },
                backimgs: [],//所有背景图
                backimgsTile: '暂未选择',
                backimgsShow: false,
                formData: {
                    id: 0,
                    title: '',
                    thumb: '',
                    content: '',
                    backimg: '',
                    music: '',
                    title_color: '#000000',
                    music_name: '',
                    hot: 1,
                    lock: 1,
                    status: 1,
                    applet:'apang'
                },
                myHeaders: {
                    'Authorization': 'Bearer ' + this.$storage.get('token'),
                    'Accept': 'application/json'
                },
                editor: null,
            }
        },
        activated() {
            this.$store.dispatch('setYuanYangActive', '/yuanyang/article');
            this.getBackgroundImg();
            this.formData = {
                id: 0,
                title: '',
                thumb: '',
                content: '',
                backimg: '',
                music: '',
                title_color: '#000000',
                music_name: '',
                hot: 1,
                lock: 1,
                status: 1,
                applet:'apang'
            };
            if(this.$route.query.id){
                this.info(this.$route.query.id);
            }
        },
        computed: {
            ...mapGetters(['loading', 'upload']),
        },
        methods: {
            //选择背景图
            select(backimg) {
                this.backimgsTile = backimg.title;
                this.formData.backimg = backimg.img;
                this.backimgsShow = false;
            },
            //上传封面
            handleAvatarSuccess(res, file) {
                this.formData.thumb = res.data;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
                const isLt2M = file.size / 1024 < 100;
                if (!isJPG) {
                    this.$message.error('上传封面图片只能是 JPG | PNG | GIF格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传封面图片大小不能超过 100KB!');
                }
                let width = 360;
                let height = 288;
                const isSize = new Promise(function (resolve, reject) {
                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function () {
                        let valid = img.width === width && img.height === height;
                        valid ? resolve() : reject();
                    };
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$message.error('上传的封面图宽高必须是' + width + '*' + height + ' PX !');
                    return Promise.reject();
                });
                return isJPG && isLt2M && isSize;
            },
            ready(editor) {
                this.editor = editor;
                if(this.$route.query.id){
                    this.info(this.$route.query.id);
                }else{
                    this.editor.setPlaceholder('请输入内容');
                }
            },
            //得到全部背景
            getBackgroundImg() {
                BackAll().then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.backimgs = response.data;
                    }
                })
            },
            info(id) {
                ArticleInfo({params: {id: id, applet: this.formData.applet}}).then((res) => {
                    this.formData = {
                        id: res.data.id,
                        title: res.data.title,
                        thumb: res.data.thumb,
                        title_color: res.data.title_color,
                        content: res.data.content,
                        backimg: res.data.backimg,
                        music: res.data.music,
                        music_name: res.data.music_name,
                        hot: res.data.hot,
                        lock: res.data.lock,
                        status: res.data.status,
                        applet:this.formData.applet
                    };
                    this.backimgs.filter((back) => {
                        if (back.img == res.data.backimg) {
                            this.backimgsTile = back.title;
                        }
                    })
                });
            },
            goback() {
                this.$router.push({name: 'APangArticle'})
            },
            //更新
            update(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        ArticleUpdate(this.formData).then((response) => {
                            if (response.code) {
                                this.$message.error(response.msg);
                            } else {
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose: () => {
                                        this.$router.push({name: 'APangArticle'})
                                    }
                                });
                            }
                        });
                    }
                });

            },
        },
    }
</script>
<style scoped>
    .backimgs {
        max-height: 550px;
        overflow: hidden;
        overflow-y: scroll;
    }
    .index-avatar-uploader .el-upload {

        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .index-avatar-uploader-icon {
        border: 1px dashed #d9d9d9;
        font-size: 28px;
        color: #8c939d;
        width: 360px;
        height: 288px;
        line-height: 288px;
        text-align: center;
    }
    .preview-art {
        background-image: url(../../assets/img/phone.png);
        background-repeat: no-repeat;
        background-size: 100% 100%;
        height: 780px;
        padding: 75px 16px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        width: 424px;
        display: inline-block;

    }
    .phone-content-title {
        background-repeat: no-repeat;
        background-size: 100% 100%;
        height: 55px;
        width: 100%;
        background-image: url(../../assets/img/titlebar.png);
    }

</style>
